#include "Image.h"
#include "../UsefullApi.h"
#include "../GuiApi.h"
#include "vmgraph.h"

static VMINT cur_image_hctrl;

void DrawImageRelease(VMINT hctrl)
{
	VMUINT8* frame_buffer = GetHDFrameBuffer();
	VMINT x, y, width, height;
	struct control_image* p = (struct control_image*)hctrl;
	x = p->p.p.x;
	y = p->p.p.y;
	width = p->p.p.width;
	height = p->p.p.height;
	
	vm_graphic_set_clip(x, y, x + width, y + height);
	
	if(p->img)
	{
		DrawImageDirect(frame_buffer, p->img, x, y, width, height);
		UpdateScreen();
	}
}

void DrawImagePress(VMINT hctrl)
{

}

void TouchImageEventHandle(VMINT tevent, VMINT x, VMINT y)
{

}

VMINT CreateImage(VMSTR img_name, VMINT is_actived, VMINT x, VMINT y, VMINT width, VMINT height)
{
	VMINT hctrl = (VMINT)vm_malloc(sizeof(struct control_image));
	struct control_image* p;

	if(hctrl == NULL)
	{
		return -1;
	}

	p = (struct control_image*)hctrl;
	memset(p, 0, sizeof(struct control_image));
	
	p->p.hctrl = hctrl;
	p->p.p.x = x;
	p->p.p.y = y;
	p->p.p.width = width;
	p->p.p.height = height;
	strcat(p->p.ctrl_name, "Image");
	p->p.ctrl_id = DM_IMAGE;
	p->p.is_focused = FALSE;
	p->p.DrawStateRelease = DrawImageRelease;
	p->p.DrawStatePress = DrawImagePress;
	p->p.touch_event_handle = TouchImageEventHandle;
	p->img_name = img_name;
	p->p.is_actived = is_actived;
	
	if(p->img_name)
	{
		p->img = get_img_by_name(p->img_name);
	}

	cur_image_hctrl = hctrl;
	return hctrl;
}

void ChangeImage(VMINT hctrl, VMSTR img_name)
{
	struct control_image* p = (struct control_image*)hctrl;
	FreeImage(hctrl);
	p->img_name = img_name;
	if(p->img_name)
	{
		p->img = get_img_by_name(p->img_name);
	}
}

void ChangeRefreshImage(VMINT hctrl, VMSTR img_name)
{
	ChangeImage(hctrl, img_name);
	RefreshImage(hctrl);
}

void ShowImage(VMINT hctrl)
{
	struct control_image* p = (struct control_image*)hctrl;

	if(p->p.is_actived == FALSE)
	{
		return;
	}
	DrawImageRelease(hctrl);
}

void RefreshImage(VMINT hctrl)
{
	ShowImage(hctrl);	
}

void FreeImage(VMINT hctrl)
{
	struct control_image* p = (struct control_image*)hctrl;
	free_img(p->img);
	vm_free(p);
	cur_image_hctrl = NULL;
}

void RegisterCurFocusedImage(VMINT hctrl)
{
	cur_image_hctrl = hctrl;
}

